package com.lzj.admin.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lzj.admin.model.CaptchaImageModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author luoyoumou
 * WeChat lym520ccy
 * <p>
 * CaptchaController
 * @version 1.0
 * @date 2022-12-04 14:11
 */
@RestController
public class CaptchaController {

    @Resource
    public DefaultKaptcha defaultKaptcha;


    /**
     *
     * @param session
     * @param response
     * @throws IOException
     */
    @GetMapping("/image")
    public void kaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        //获取生成验证码文字
        String capText=defaultKaptcha.createText();

        //将验证码存入 session 并设置过期时间2分钟，2*60更清晰
        session.setAttribute("captcha_key",new CaptchaImageModel(capText,2*60));

        ServletOutputStream out = response.getOutputStream();
        //输出IO
        BufferedImage bufferedImage=defaultKaptcha.createImage(capText);
        //告诉浏览器输出的是jpg
        ImageIO.write(bufferedImage,"jpg",out);
        //刷新缓存
        out.flush();

    }


}
